
function appendToMasterPage(page,id,header,footer){
    console.log("appendToMasterPage called");
    var header_nav = "";    
    if(id=='addtypes'){
        header_nav += "<a href='#home' data-icon='home' data-iconpos='notext'></a>";
    }else{
        header_nav += "<a href='#home' data-icon='home' data-iconpos='notext'></a>";
        header_nav += "<a  data-icon='back'  data-role='button' data-rel='back' data-iconpos='notext'></a>";
           
    }

    var output = "<div data-role='page' id='"+ id +"'>";
    output += "<div data-role='header' data-add-back-btn='' data-position='fixed'>";
    output += "<h1>" + header + "</h1>";
    output += header_nav;
    output+= "</div>";
    output += page;
    output+= "<div data-role='footer' id='mainFooter' data-position='fixed'>";
    output+="<div data-role='navbar' id='catSizesBtn'>"+footer+"</div>";
    output += "<h1>Powered by Tekmonkeys</h1></div>";
    $("#master_page").append(output);
    $('#' + id).page();
    //refresh whole page
    $('#master_page').trigger("create");
   
}

function doesPageExist(id){
   if ($("#" + id).length > 0){
       console.log("page " + id + " exists");
        return true;
   }       
    else{
        console.log("page " + id + " does not exists");
        return false;
    }
        
       
}


function loadPage(page){
    console.log("loadPage called.");
    $.mobile.changePage("#"+page,{transition:"flow"});
}

function loadPHP(page){
     console.log("loadPHP called.");
   
    $.mobile.changePage(page);
}

function loadAddTypes(){
    var url = location.protocol + '//'+ location.host;
    if(!doesPageExist('addtypes')){
        console.log("addtyps page does not exists")
        $.getJSON(url + "/index.php/addcontroller/showAddTypes", function (data) {
            console.log(data);
            var output = "<ul data-role='listview' data-filter='true'  class='typelist'>";
            $.each(data, function (i, item) {
                output += "<li data-theme='c'  data-name='" + item.id + "'><a href='#" + item.id + "' class='catbtn'  >" + item.name + "</a></li>";
            });
            output += " </ul>";
            //$("#clist").html(output);
            appendToMasterPage(output, 'addtypes', 'Choose AD Type', '');
            $(".typelist").listview();
            loadPage('addtypes');



        });
    }else{
       console.log("addtype page exists");
       loadPage('addtypes');
      
    }


   
    

    
}

function loadTypeCategories(type){

    var url = location.protocol + '//'+ location.host;
    var page = 'category_' + type;
    setSelectedAddType(type);
    if(!doesPageExist(page)){
        console.log("category page does not exists")
        $.getJSON(url + "/index.php/addcontroller/showTypeCategories/" + type, function (data) {
            var output = "<ul data-role='listview' data-filter='true'  class='catlist'>";
            $.each(data, function (i, item) {
                console.log("item=" + item.catid);
                output += "<li data-theme='c'  data-name='" + item.catid + "'><a href='#" + item.catid + "' class='catbtn'  >" + item.name + "</a></li>";
            });
            output += " </ul>";
            //$("#clist").html(output);
            
            appendToMasterPage(output, page, type + ' > Categories', '');
            $(".catlist").listview();
            loadPage(page);

        });
    }else{
       console.log("category page exists");
       loadPage(page);
    }

    
  
}

function loadCategoryItems(cat){

    console.log("loadCategoryItems="+cat);
    var type = $("#typeSelected").val();
    var url = location.protocol + '//'+ location.host;
    var page = "products_" + cat + "_" + type;
    var chkgroup = type + "_" + cat;
    if(!doesPageExist(page)){

        $.getJSON(url + "/index.php/addcontroller/showCatItems/" + cat + "/" + type, function (data) {


            var output = "<ul data-role='listview' data-split-icon='gear' data-filter='true' id='" + chkgroup +"'>";

            $.each(data, function (i, item) {
                output += "<li>";
                output += "<label style='border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;' data-corners=false'>";
                output += "<fieldset data-role='controlgroup'>";
                output += "<input type='checkbox' style='border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;' id='" + item.id + "' name='" + item.name + "'>";
                output += "<label for='" + item.id + "'style='border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;'>";
               // output += "<img src='Images/Sensor_Icon.png' style='float:left;width:80px;height:80px'/>";
                output += "<label style='float:left;padding:10px 0px 0px 10px;'>";
                output += "<h3>" + item.name + "</h3>";
                output += "<p>Price:</p><p>Weekdays: <b>Php" + item.wkday_price + " / col cm</b><br/><p>Weekends: <b>Php"+  item.wkend_price +" / col cm</b><br/></p> ";
             
                output += "</label>";
                output += "</label>";
                output += "</fieldset>";
                output += "</label>";
              


                //output += "<label for='" + key + "'>" + val + "</label>";
                // output += "<img src=img/test.jpg/>"
                // output += "<input type='checkbox' id='" + key + "' name='" + val + "'>";
                //output += "<h1>"+ val + "</h1>";
               // output += "<p>Price:</p><p>Weekdays: <b>Php 371.00 / col cm</b><br/><p>Weekends: <b>Php 427.00 / col cm</b><br/></p> ";
                output += "</li>";
            });
            output += " </ul>";
            var header = "";
            if (cat == 'cat-0001')
                header = "Select Newspapers";
            if (cat == 'cat-0002')
                header = "Select Magazines";
            if (cat == 'cat-0003')
                header = "Select Tabloids";

            //add the next button to the main footer
            //output += "<a data-role='button' id='catSizesBtn' onclick='loadCategorySizes()' data-theme='b'>Next</a>";
            var footer = "<ul><li><a data-role='button'   onclick='loadCategorySizes()' data-theme='b' data-icon='arrow-r' data-iconpos='notext'></a></li></ul>";
            setSelectedCategory(cat);
            appendToMasterPage(output, page, header, footer);
            loadPage(page);


        });
    }else{
       console.log("product page exists:=" + page);
       loadPage(page);
      
    }

      
          

    
}

function loadCategorySizes(){
    var cat = $('#catSelected').val();
    var type = $('#typeSelected').val();
    //var page = "sizes_" + cat + "_" + type;
    var page ="add_details";
    setSelectedCategory(cat);
    getSelectedProducts(type+"_"+cat);
    console.log("loading sizes for category=" +cat );
    var url = location.protocol + '//'+ location.host;
    //if(!doesPageExist(page)){

        $.getJSON(url + "/index.php/addcontroller/showCatetorySizes/" + cat, function (data) {


            var cols = '';
            var rows = '';
            $.each(data, function (key, val) {
                if (key == 'cols')
                    cols = val;
                else
                    rows = val;
            });

            console.log("cols=" + cols);
            console.log("rows=" + rows);

            var output = "<form id='addDetails'>";
            output += "<div data-role=collapsible-set>";
            output += "<div data-role=collapsible>";
            output += "<h1>Specify Size</h1>"
            output += "<span>Choose number of columns</span><br/>";
            output += "<input type='range' min='1' max='" + cols + "' id='" + cat + "_cols'/>";
            output += "<span>Choose number of rows</span><br/>";
            output += "<input type='range' min='1' max='" + rows + "' id='" + cat + "_rows'/>";
            output += "</div>";
            output += "<div data-role=collapsible>";
            output += "<h1>Specify AD Dates</h1>";
            output += "<span>Start Date</span><br/>";
            output += "<input type='date' placeholder='Start Date' id='startDate'/>"
            output += "<span>End Date</span><br/>";
            output += "<input type='date' placeholder='End Date' id='endDate'/>"
            output += "</div>";
            output += "<div data-role=collapsible>";
            output += "<h1>AD Content</h1>";
            //output += "<span>Title</span><br/>";
            output += "<input type=text placeholder='Title' name='ad_title' id='ad_title'/>"
            //output += "<span>Description</span><br/>";
            output += "<textarea rows=10 placeholder='Description' class='ui-input-text ui-body-c ui-corner-all ui-shadow-inset' name='ad_desc' id='ad_desc'></textarea>"
            output += "<span>Attach files(MS Word,JPEG,PNG)</span><br/>";
            //output += "<input type='file' name='file' id='file' class='ui-input-text ui-body-c'/>";
            output += "<div id='container'>";
            output += "<div id='filelist' >No runtime found</div><br/>";
            //output += "<div id='filelist' ></div><br/>";
            output += "<fieldset class='ui-grid-a'>";
            output += "<div class='ui-block-b'><a id='pickfiles' href='#' data-role='button' data-mini=true data-icon='plus' data-iconpos='top' data-theme='a'> Select Files </a></div>";
           // output += "<div class='ui-block-b'><a id='uploadfiles' href='#' data-role='button' data-mini=true data-icon='check' data-iconpos='top' data-theme='a'> Upload files </a></div>";
            output += "</fieldset>";
            output += "</div>";
            //output += "<a data-role='button' data-theme='b' onclick='uploadImage()'>upload</a>";
            output += "</div>";
            output += "</div>"; //end of collapsible-set
            output += "</form>";



            var header = "";
            if (cat == 'cat-0001')
                header = "Newspaper AD Details";
            if (cat == 'cat-0002')
                header = "Magazines AD Details";
            if (cat == 'cat-0003')
                header = "Tabloids AD Details";

            //add the next button to the main footer
            //output += "<a data-role='button' id='catSizesBtn' onclick='loadCategorySizes()' data-theme='b'>Next</a>";
            var footer = "<ul><li><a data-role='button'   data-ajax='false' onclick='loadAddDetailsPage2()' data-theme='b' data-icon='arrow-r' data-iconpos='notext'></a></li></ul>";
            
            appendToMasterPage(output, page, header, footer);
            // $('#uploadBtn').button();
            loadPage(page);


        });
   /* }else{
       console.log("sizes page exists:=" + page);
       loadPage(page);
      
    }*/

    


}

function loadAddDetailsPage(){
    console.log("loadAddDetailsPage called");
    var type = $("#typeSelected").val();
    var cat = $('#catSelected').val();
    var col = $("#" + cat + "_cols").val();
    var rows = $("#" + cat + "_rows").val();
    var sDate = $("#startDate").val();
    var eDate = $("#endDate").val();
    var products = $('#prodSelected').val();
    var adtitle = $('#ad_title').val();
    var addesc = $('#ad_desc').val();
    getFilesSelected();
    console.log("type=" + type);
    console.log("category=" + cat);
    console.log("cols=" + col);
    console.log("rows=" + rows);
    console.log("start date=" + startDate);
    console.log("end date=" + endDate);
    console.log("products selected=" + products);
    console.log("Ad Title=" + adtitle);
    console.log("Ad Desc=" + addesc);
    var adds_page = 'ads_page_' + type + "_" +cat + '_' + products + '_' + col + '_' + rows + '_' + sDate + '_' + eDate;
    var output = "";
    var url = location.protocol + '//'+ location.host; 
    //retrieve prices for each product selected
    if(!doesPageExist(adds_page)){
      
        $.ajax({
            url: url + "/index.php/addcontroller/showAddDetails/" + type + '/' + cat + '/' + products + '/' + col + '/' + rows + '/' + sDate + '/' + eDate + '/' + adtitle + '/' + addesc,
            complete: function (xhr, result) {
                if (result != "success") return;
                var response = xhr.responseText;
                 var footer = "<ul><li>";
                 footer+="<a data-role='button'   onclick='loadAddTypes()' data-theme='b' >add more</a></li>";
                 footer+= "<li><a data-role='button'   onclick='loadCheckoutPage()' data-theme='b' >checkout</a></li></ul>"
           
                 appendToMasterPage(response, adds_page, "Ad Details", footer);
                 loadPage(adds_page);
            }
        });
    }else{
       console.log(adds_page + ' exists'); 
       loadPage(adds_page);
    }


}

function loadAddDetailsPage2(){
    console.log("loadAddDetailsPage called");
    var type = $("#typeSelected").val();
    var cat = $('#catSelected').val();
    var col = $("#" + cat + "_cols").val();
    var rows = $("#" + cat + "_rows").val();
    var sDate = $("#startDate").val();
    var eDate = $("#endDate").val();
    var products = $('#prodSelected').val();
    var adtitle = $('#ad_title').val();
    var addesc = $('#ad_desc').val();
    getFilesSelected();
    console.log("type=" + type);
    console.log("category=" + cat);
    console.log("cols=" + col);
    console.log("rows=" + rows);
    console.log("start date=" + startDate);
    console.log("end date=" + endDate);
    console.log("products selected=" + products);
    console.log("Ad Title=" + adtitle);
    console.log("Ad Desc=" + addesc);
    var adds_page = 'ads_page_' +type+"_"+ cat + '_' + products + '_' + col + '_' + rows + '_' + sDate + '_' + eDate;
    var output = "";
    var url = location.protocol + '//'+ location.host; 
    //retrieve prices for each product selected
    if(!doesPageExist(adds_page)){
      
        $.ajax({
            //url: url + "/index.php/addcontroller/showAdDetails/",
            url: url + "/index.php/addcontroller/addToCart/",
            method: "post",
            data: {type:type,cat:cat,col:col,row:rows,sdate:sDate,edate:eDate,products:products,title:adtitle,desc:addesc},
            complete: function (xhr, result) {
                if (result != "success") return;
                var response = xhr.responseText;
                 var footer = "<ul><li>";
                 footer+="<a data-role='button'   onclick='loadAddTypes()' data-theme='b' >add more</a></li>";
                 footer+= "<li><a data-role='button'   onclick='loadCheckoutPage()' data-theme='b' >checkout</a></li></ul>"
           
                 appendToMasterPage(response, adds_page, "Ad Details", footer);
                 loadPage(adds_page);
            }
        });
    }else{
       console.log(adds_page + ' exists'); 
       loadPage(adds_page);
    }


}

function loadCheckoutPage(){
    var page = "checkout";
    var html = "<ul data-role='listview' data-theme='c'>";
    html+="<li data-theme='b'  data-name='paypal'>";
    //html +="<img src='img/pp_buynow.png'/>";
    html += "<a href='#'> PAYPAL</a>";
    html +="</li>";
    html +="<li data-theme='b'  data-name='gcash'>";
   // html +="<img src='img/gcash.jpg' />";
    html += "<a href='#'> GCASH</a>";
    html +="</li>";
    html +="<li data-theme='b'  data-name='smart'>";
    //html +="<img src='img/smartmoney.png'/>";
    html += "<a href='#'> SMART MONEY</a>";
    html +="</li>";
    html +="</ul>";

     if(!doesPageExist(page)){
         appendToMasterPage(html,page,"Checkout","");
     }else{
         loadPage(page);
     }
    




}

function deleteItemFromCart(param){
    var item = param.split('_');
    var prodid = item[0];
    var typeid = item[1];
    var userid = item[2];
    console.log('item to delete from cart:' + prodid + "|" + typeid + "|" + userid);

    var update_cart_page = "update_cart_" + prodid + "_" + typeid + "_" + userid;
    var url = location.protocol + '//'+ location.host; 
    //retrieve prices for each product selected
    //if(!doesPageExist(update_cart_page)){
      
        $.ajax({
            //url: url + "/index.php/addcontroller/showAdDetails/",
            url: url + "/index.php/addcontroller/deleteItemFromCart/",
            method: "post",
            data: {typeid:typeid,prodid:prodid,userid:userid},
            complete: function (xhr, result) {
                if (result != "success") return;
                var response = xhr.responseText;
                 var footer = "<ul><li>";
                 footer+="<a data-role='button'   onclick='loadAddTypes()' data-theme='b' >add more</a></li>";
                 footer+= "<li><a data-role='button'   onclick='loadCheckoutPage()' data-theme='b' >checkout</a></li></ul>"
           
                 appendToMasterPage(response, update_cart_page, "Ad Details", footer);
                 loadPage(update_cart_page);
            }
        });
    /*}else{
       console.log(update_cart_page + ' exists'); 
       loadPage(update_cart_page);
    }*/


}

function uploadImage(){
     console.log("uploadImage called" );
    var url = location.protocol + '//'+ location.host;

    var formData = new FormData();
    $.each($('#addDetails').find("input[type='file']"), function (i, tag) {
        $.each($(tag)[0].files, function (i, file) {
            formData.append(tag.name, file);
        });

    });

    var params = $('#addDetails').serializeArray();
    $.each(params, function (i, val) {
        formData.append(val.name, val.value);
    });

    $.ajax({

        type: "POST",
        contentType: false,
        processData:false,
        cache:false,
        url: url + "/index.php/addcontroller/uploadFiles",
        data: formData,
        success: function (data) {
            alert(data);
        }
    });

}
function login(){
     var url = location.protocol + '//'+ location.host;
     var uname = $("#uname").val();
     var pass = $("#pass").val();
     var credentials = { username: uname, password: pass };
     $.ajax({
         type: "POST",
         url: url + "/index.php/addcontroller/logon/",
         cache: false,
         data: JSON.stringify(credentials),
         contentType: "application/json;charset=utf-8",
         complete: function (xhr, result) {
             if (result != "success") return;
             var response = xhr.responseText;
             console.log("response=" + response);
             if (response != "1") {
                 loadPage("home");
             }



         }
     });

}

function open(){
    console.log("open method called");
     var url = location.protocol + '//'+ location.host;
    
     $.ajax({
         url: url + "/index.php/addcontroller/open",
         complete: function (xhr, result) {
             if (result != "success") return;
             var response = xhr.responseText;
             console.log(response);
            
             // appendToMasterPage(response, adds_page, "Ad Details", "");
             // loadPage(adds_page);
         }
     });
}

function setSelectedCategory(param){
    $("#catSelected").val('');
    $("#catSelected").val(param);
}

function setSelectedAddType(param){
    $("#typeSelected").val('');
    $("#typeSelected").val(param);
}

function setSelectedProducts(param){
    $("#prodSelected").val('');
    $("#prodSelected").val(param);
}

function getFilesSelected(){
    console.log("files selected");
    var files = "";
    $("#filelist").children('div').each(function(){
        var fileid= $(this).attr('id');
        var filename = $(this).html();
        console.log("file id=" + fileid);
        console.log("file name=" + filename);

    });
    
}

function getSelectedProducts(elem){
     //see which checkboxes where selected
      var prods = '';
      $('#' + elem +" :checkbox").each(function () {
          var name = $(this).attr('name');
          var key = $(this).attr('id');
          var value = $(this).val();

          if ($(this).prop('checked')) {
              prods += key + "_";
              console.log("product key=" + key);
              console.log(name, value);
          }
         
      });

       if (prods.lastIndexOf('_') == prods.length - 1) {
              console.log("last character is a pipe");
              //remove last comma
              prods=prods.substring(0, prods.length-1);
          }
          setSelectedProducts(prods);
}


 function initUploader() {
                var uploader = new plupload.Uploader({
                    runtimes: 'gears,flash,silverlight,browserplus,html5',
                   // runtimes: 'flash,html5',
                    
                    browse_button: 'pickfiles',
                    container: 'container',
                    url: "/index.php/addcontroller/upload",
                    max_file_size: '10mb',
                    unique_names: true,
                    //resize images on client side
                    resize: { width: 320, height: 240, quality: 90 },
                    //specify which files to browse for
                    filters: [
                       { title: "Image files", extensions: "jpg,gif,png" },
                       {title:"Zip files",extensions:"zip"}
                    ]

                });
                uploader.refresh();
                //$('#pickfiles > div.plupload').css('z-index','99999');

                uploader.bind('Init', function (up, params) {
                    $('#filelist').html("<div>Current runtime: " + params.runtime + "</div>");
                });

                $("#uploadfiles").click(function (e) {
                    uploader.start();
                    e.preventDefault();
                })

                uploader.init();

                uploader.bind('FilesAdded', function (up, files) {
                    var file_names = "";
                    var file_ids = "";
                    $.each(files, function (i, file) {
                        console.log("file id=" + file.id);

                        $('#filelist').append("<div id='" + file.id + "'>" + file.name + " (" + plupload.formatSize(file.size) + ") <b id=b_" + file.id + "> </b></div>");

                    });
                    up.refresh();
                    uploader.start();
                });

                uploader.bind('UploadProgress', function (up, file) {
                    $.mobile.loading('show');

                    console.log("UploadProgress=" + file.percent);
                    $("#b_" + file.id).html(file.percent + "%");
                });

                uploader.bind('Error', function (up, err) {
                    $('#filelist').append("<div>Error: " + err.code + ", Message: " + err.message + (err.file ? ", File: " + err.file.name : "") + "</div>");
                    up.refresh();
                });

                uploader.bind('FileUploaded', function (up, file) {
                    console.log('FileUploaded');
                    $.mobile.loading('hide');

                    $("#b_" + file.id).html("100%");
                })


            }


